package com.bizihang.common.security.core.code;

import com.bizihang.common.security.core.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.EnumMap;

/**
 * 生成校验码的请求处理器
 *
 * @author 毕子航 951755883@qq.com
 * @date 2018/10/24
 */
@Slf4j
@RestController
public class ValidateCodeController {
	@Autowired
	private ValidateCodeProcessorHolder validateCodeProcessorHolder;

	/**
	 * 创建验证码，根据验证码类型不同，调用不同的 {@link ValidateCodeProcessor}接口实现
	 *
	 * @param request  the request
	 * @param response the response
	 * @param type     the type
	 * @throws Exception the exception
	 */
	@PostMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}")
	public void createCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) throws Exception {
		validateCodeProcessorHolder.findValidateCodeProcessor(type).create(new ServletWebRequest(request, response));
	}

	/**
	 * Check code object.
	 *
	 * @param request  the request
	 * @param response the response
	 * @param type     the type
	 * @return the object
	 */
	@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}")
	public Object checkCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) {
		EnumMap enumMap = new EnumMap(SecurityConstants.RetEnum.class);
		enumMap.put(SecurityConstants.RetEnum.success, true);
		enumMap.put(SecurityConstants.RetEnum.body, "校验成功");
		try {
			validateCodeProcessorHolder.findValidateCodeProcessor(type).check(new ServletWebRequest(request, response));
		} catch (ValidateCodeException e) {
			if (log.isDebugEnabled()) {
				e.printStackTrace();
			}
			enumMap.put(SecurityConstants.RetEnum.success, false);
			enumMap.remove(SecurityConstants.RetEnum.body);
		} catch (Exception e) {
			if (log.isDebugEnabled()) {
				e.printStackTrace();
			}
			enumMap.put(SecurityConstants.RetEnum.success, false);
			enumMap.put(SecurityConstants.RetEnum.body, "验证码错误");
			log.error("getAccessToken={}", e.getMessage(), e);
		}
		return enumMap;
	}
}
